import tornado.websocket
import tornado.web,random
from db import db
from util.myredis import r
conndict={}
userlist = []
import json
class WebusersockHandler(tornado.websocket.WebSocketHandler):
    # 跨域支持
    def check_origin(self, origin):
        return True
    #建立连接
    def open(self):
        #获取参数
        id = str(self.get_query_argument("id"))
        mobile = str(self.get_query_argument("mobile"))
        #存储链接
        # 存储用户连接
        conndict[id]=self
        # 判断是否为用户，如果为用户加入userlist
        index = id.find('kefu')
        if index >=0:
            self.write_message({'userlist':userlist,'mes':{}})
        else:
            userlist.append({'id': id, 'mobile': mobile})
            key = 'levelmes' + str(id)
            mm = r.str_get(key)
            if mm:
                mm = mm.decode()
                self.write_message({'userlist': [], 'mes': mm})
        print(userlist)
        print(conndict[id])
    #接收消息
    def on_message(self,mes):
        mes = json.loads(mes)
        id = mes['id']
        mes = mes['mes']
        # 如果在线直接发
        if id in conndict:
            conndict[id].write_message({'userlist':userlist,'mes':mes})
        else:
            # 用户离线 加入redis
            key = 'levelmes'+str(id)
            r.str_add(key,mes)

    def on_close(self):
        pass
